package com.csw.shuanfa.CodeImprove.designPattern;

import java.util.ArrayList;
import java.util.List;

//观察者接口
interface Observer {
    void update(String message);
}

//主题接口
interface Subject {
    void registerObserver(Observer observer);

    void removeObserver(Observer observer);

    void notifyObserver(String message);
}

/**
 * 观察者模式
 */
public class ObserverD {
    /**
     * @param args
     */
    public static void main(String[] args) {
        concreteSubject subject = new concreteSubject();
        Observer observer1 = new ConcreteObserver1();
        Observer observer2 = new ConcreteObserver2();
        subject.registerObserver(observer1);
        subject.registerObserver(observer2);
        subject.notifyObserver("观察者模式测试");
    }
}

//具体观察者1
class ConcreteObserver1 implements Observer {

    @Override
    public void update(String message) {
        System.out.println("ConcreteObserver1:" + message);

    }
}

//具体观察者2
class ConcreteObserver2 implements Observer {

    @Override
    public void update(String message) {
        System.out.println("ConcreteObserver2:" + message);

    }
}

//具体主题
class concreteSubject implements Subject {
    private final List<Observer> list = new ArrayList<>();

    @Override
    public void registerObserver(Observer observer) {
        list.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        list.remove(observer);
    }

    @Override
    public void notifyObserver(String message) {
        for (Observer observer : list) {
            observer.update(message);
        }
    }
}